/*
 * "TypeParser.java" is part of Tarinca-COA
 * (http://code.google.com/p/taringa-api/)
 * Copyright (C) - 2010 Juan B Cabral <jbc dot develop at gmail dot com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package taringa;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Parseador de tipos
 *
 * @version 0.2
 * @license LGPL3
 * @author JBC
 * @since 0.2
 * @date 2010-02-13
 */
abstract class TypeParser {

    private static SimpleDateFormat dateFormat =
            new SimpleDateFormat("y-M-d h:m:s");

    /**
     * Retorna el objeto como long.
     * @param obj objeto a convertir.
     * @return el objeto como long.
     */
    public synchronized static long toLong(Object obj) {
        if (obj != null) {
            String str = String.valueOf(obj);
            return Long.parseLong(str);
        }
        return 0;
    }

    /**
     * Retorna el objeto como boolean.
     * Se parsean como falsos valores que al parsearse a string son iguales a
     * null, false, 0, 0.0, ""
     *
     * @param obj objeto a convertir.
     * @return el objeto como boolean.
     */
    public synchronized static boolean toBoolean(Object obj) {
        String str = String.valueOf(obj).trim();
        return !(str.matches("null|false|0*|0*\\.0*") || str.isEmpty());
    }

    /**
     * Retorna el objeto como Date.
     * @param obj objeto a convertir.
     * @return el objeto como Date.
     */
    public synchronized static Date toDate(Object obj) {
        String str = String.valueOf(obj);
        try {
            return TypeParser.dateFormat.parse(str);
        } catch (ParseException ex) {
            throw new TaringaError(ex.getMessage(), 1000, ex.getStackTrace());
        }

    }
}
